<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <el-form-item label="中文名称" prop="cnName">
                    <el-input v-model="formData.cnName" placeholder="请输入中文名称" />
                </el-form-item>
                <el-form-item label="英文名称" prop="usName">
                    <el-input v-model="formData.usName" placeholder="请输入英文名称" />
                </el-form-item>
                <el-form-item label="宣传图片" prop="images">
                    <div class="image-upload-container">
                        <div class="flex items-start gap-3">
                            <el-upload
                                :show-file-list="false"
                                :http-request="handleSingleImageUpload"
                                :before-upload="beforeSingleImageUpload"
                                accept="image/*"
                            >
                                <el-button size="small" type="primary">选择图片</el-button>
                            </el-upload>
                            <div v-if="formData.images" class="flex-1">
                                <el-image 
                                    :src="formData.images" 
                                    style="width: 100px; height: 100px" 
                                    fit="cover"
                                    :preview-src-list="[formData.images]"
                                />
                                <div class="text-xs text-gray-500 mt-1 break-all">{{ formData.images }}</div>
                            </div>
                            <el-button 
                                v-if="formData.images"
                                type="danger" 
                                size="small" 
                                @click="removeSingleImage"
                            >
                                删除
                            </el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="宣传视频" prop="video">
                    <el-input v-model="formData.video" placeholder="请输入宣传视频" />
                </el-form-item>
                <el-form-item label="简介" prop="detail">
                    <el-input v-model="formData.detail" placeholder="请输入简介" />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import {  brandEdit, brandAdd, brandDetail } from '@/api/brand'
import { uploadImg } from '@/api/uploads'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑品牌' : '新增品牌'
})

const formData = reactive({
    id: '',
    cnName: '',
    usName: '',
    images: '',
    video: '',
    detail: '',
})

// 图片上传相关方法

const formRules = {
    id: [
        {
            required: true,
            message: '请输入',
            trigger: ['blur']
        }
    ],
    cnName: [
        {
            required: true,
            message: '请输入中文名称',
            trigger: ['blur']
        }
    ],
    usName: [
        {
            required: true,
            message: '请输入英文名称',
            trigger: ['blur']
        }
    ],
    images: [
        {
            required: false,
            message: '请上传宣传图片',
            trigger: ['blur']
        }
    ],
    video: [
        {
            required: false,
            message: '请输入宣传视频',
            trigger: ['blur']
        }
    ],
    detail: [
        {
            required: false,
            message: '请输入简介',
            trigger: ['blur']
        }
    ],
}

// 图片上传相关方法
const beforeSingleImageUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isImage) {
        feedback.msgError('只能上传图片文件!')
        return false
    }
    if (!isLt10M) {
        feedback.msgError('图片大小不能超过 10MB!')
        return false
    }
    return true
}

const handleSingleImageUpload = async (options: any) => {
    try {
        const uploadFormData = new FormData()
        uploadFormData.append('file', options.file)
        
        const response = await uploadImg(uploadFormData)
        if (response && response.url) {
            formData.images = response.url
            feedback.msgSuccess('图片上传成功')
        }
    } catch (error) {
        console.error('图片上传失败:', error)
        feedback.msgError('图片上传失败')
    }
}

const removeSingleImage = () => {
    formData.images = ''
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = { ...formData }
    mode.value == 'edit' ? await brandEdit(data) : await brandAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    if (type === 'add') {
        // 重置图片
        formData.images = ''
    }
    popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await brandDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
